package ltd.hyangyang.vegetable.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import ltd.hyangyang.vegetable.entity.User;
import ltd.hyangyang.vegetable.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
public class VegetableInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前的ip
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
        User user = userService.getByAddr(remoteAddr);
        if (request.getHeader("account")!=null){
            return true;
        }
        if (!ObjectUtils.isEmpty(user)){
            //数据库中存在该用户，放行
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();

            updateWrapper.eq("user_id",user.getUserId()).set("user_visits",user.getUserVisits()+1);
            userService.update(updateWrapper);
            return  true;
        }
        //数据库中不存在该用户，添加用户
        user = new User();
        user.setUserVisits(0);
        user.setIp(remoteAddr);
        user.setCreateTime(LocalDateTime.now());
        userService.save(user);
        return true;
    }
}
